//
//  UIImage+Extension.swift
//  BTE
//
//  Created by Mike Zhang on 2025/8/14.
//

import UIKit
import ImageIO


// MARK: - UIImage 扩展 (辅助功能)
extension UIImage {
    /// 创建1x1像素的纯色图像
    static func onePixelImage(color: UIColor) -> UIImage? {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        
        context.setFillColor(color.cgColor)
        context.fill(rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image
    }
}



extension UIImage {
    
    /// 压缩图片数据到指定最大字节大小
    /// - Parameter maxSize: 最大字节大小 (单位: bytes)
    /// - Returns: 压缩后的图片数据
    public func compressedImageData(maxSize: Int) -> Data? {
        // 1. 初始压缩尝试
        guard let initialData = compressWithQuality(maxSize: maxSize) else {
            return jpegData(compressionQuality: 0.8) // 如果无法压缩，返回默认质量图片
        }
        
        // 2. 检查是否满足大小要求
        if initialData.count <= maxSize {
            return initialData
        }
        
        // 3. 缩放压缩
        return compressByScaling(maxSize: maxSize, initialData: initialData)
    }
    
    /// 通过质量压缩图片
    private func compressWithQuality(maxSize: Int) -> Data? {
        let compressionQualityRange: ClosedRange<CGFloat> = 0.1...1.0
        var compressionQuality: CGFloat = 1.0
        
        // 初始压缩尝试
        guard var compressedData = jpegData(compressionQuality: compressionQuality) else {
            return nil
        }
        
        // 如果初始数据已满足要求
        if compressedData.count <= maxSize {
            return compressedData
        }
        
        // 二分法查找最佳压缩质量
        var low: CGFloat = compressionQualityRange.lowerBound
        var high: CGFloat = compressionQualityRange.upperBound
        
        for _ in 0..<8 { // 最多尝试8次
            compressionQuality = (low + high) / 2
            guard let newData = jpegData(compressionQuality: compressionQuality) else { break }
            
            if newData.count < maxSize {
                low = compressionQuality // 质量可以更高
                compressedData = newData
            } else {
                high = compressionQuality // 质量需要更低
            }
        }
        
        return compressedData
    }
    
    /// 通过缩放压缩图片
    private func compressByScaling(maxSize: Int, initialData: Data) -> Data? {
        guard let sourceImage = UIImage(data: initialData) else { return initialData }
        var currentImage = sourceImage
        var currentData = initialData
        
        // 逐步缩小图片直到满足大小要求
        while currentData.count > maxSize {
            // 计算缩放比例 (每次缩小10%)
            let scaleFactor: CGFloat = 0.9
            let newSize = CGSize(
                width: currentImage.size.width * scaleFactor,
                height: currentImage.size.height * scaleFactor
            )
            
            // 使用UIGraphics渲染缩放图片
            UIGraphicsBeginImageContextWithOptions(newSize, true, currentImage.scale)
            currentImage.draw(in: CGRect(origin: .zero, size: newSize))
            guard let scaledImage = UIGraphicsGetImageFromCurrentImageContext() else {
                UIGraphicsEndImageContext()
                break
            }
            UIGraphicsEndImageContext()
            
            // 尝试使用新图片
            guard let newData = scaledImage.jpegData(compressionQuality: 0.85) else { break }
            
            // 检查是否达到最小尺寸限制
            if newSize.width < 100 || newSize.height < 100 {
                return newData // 防止图片过小
            }
            
            currentImage = scaledImage
            currentData = newData
        }
        
        return currentData
    }
    
    /// 高效缩放图片到指定尺寸
    public func resizedImage(targetSize: CGSize) -> UIImage? {
        let renderer = UIGraphicsImageRenderer(size: targetSize)
        return renderer.image { _ in
            self.draw(in: CGRect(origin: .zero, size: targetSize))
        }
    }
    
    /// 获取图片的元数据
    public var metadata: [String: Any]? {
        guard let data = jpegData(compressionQuality: 1.0) else { return nil }
        guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }
        guard let metadata = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [String: Any] else { return nil }
        return metadata
    }
    
    /// 获取图片的文件大小 (单位: bytes)
    public var fileSize: Int? {
        return jpegData(compressionQuality: 1.0)?.count
    }
    
}
